#include <time.h>
#include "door_interface.h"
#define MAX_USERS 256

typedef struct user {
  char cardID[66];
  char uname[64];
  //TODO: add time slot;
  
} GNUuser;
int number_of_users;
GNUuser user[MAX_USERS];

int auth(char * buff,GNUuser* user,int number_of_users){
  int i;
  //TODO: add time slot
  for(i=0;i<number_of_users;i++)
    if( 0 == strcmp(buff, (user[i].cardID))){
      printf("UID:%d",i);
      return i;
    }

  return -1;
}

int main( int argc, char* argv[] ){
  int fd;
  char buff[256];
  if(argc != 3){
    fprintf(stderr,"Error: Wrong number of args.\nUsage %s <config-file> /dev/<device-name>\n",argv[0]);
    exit(-1);
  }
  else {
    FILE* config = fopen(argv[1],"r");
    fscanf(config,"%d\n",&number_of_users);
    int i;
    printf("no of users:%d\n", number_of_users); 
    for(i=0;i<number_of_users;i++){
      fscanf(config,"%s %s\n",user[i].cardID,user[i].uname);
      printf("%s: %s\n", user[i].uname, user[i].cardID);
    }
    fclose(config);

    //now initialize the device
    if( (fd = serial_init(argv[2])) > 0){
      while(1){
	int userID;
	serial_readln(fd,buff,255);//TODO: handle errors
	userID = auth(buff,user,number_of_users);
	if( (userID >= 0) ){
	   printf("door_open: %d\n",door_open(fd,3)); //TODO: handle errors
	  printf("RFID: %s\n",(user[userID].uname));
	}
      }
    }
    else
      exit(-2);
  }
  
  return 0;
}
